package com.ganbo.thread;

/**
 * 死锁
 * Created by gan on 2020/5/20 4:00.
 */
public class DeathLockDemo implements Runnable {

    private String name;

    private Object o1 = new Object();
    private Object o2 = new Object();

    public void setName(String name) {
        this.name = name;
    }

    public void run() {
        try {
            if ("a".equals(name)) {
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName() + "===================a 准备去获取锁o2...");
                    Thread.sleep(3000);

                    synchronized (o2) {
                        System.out.println(Thread.currentThread().getName() + "===================a 获取到锁o2...");
                    }
                }
            } else {
                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName() + "===================a 准备去获取锁o1...");
                    Thread.sleep(3000);
                    synchronized (o1) {
                        System.out.println(Thread.currentThread().getName() + "===================a 获取到锁o1...");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DeathLockDemo d = new DeathLockDemo();
        d.setName("a");
        Thread t1 = new Thread(d);
        t1.start();

        Thread.sleep(1000);

        d.setName("b");
        Thread t2 = new Thread(d);
        t2.start();
    }
}
